<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/17 0017
 * Time: 上午 9:41
 */

namespace App\Logic;


use App\Extend\Wx\Wx;
use App\Guest;
use Carbon\Carbon;
use Cache;
class WxLogin
{
    /**
     * 根据小程序提交的code进行登录
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model Guest
     * @throws \App\Exceptions\WxLoginException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function login($code)
    {
//        config('xcx')
        $result = (new Wx(config('xcx')))->login($code);
        $user =  Guest::firstOrCreate(['wx_id'=>$result->openid]);
        Cache::set($user->id,$result,Carbon::now()->addSecond(7000));
        return $user;
    }

    /**
     * @param $user
     * @param $encryptedData
     * @param $iv
     * @return bool
     * @throws \Exception
     */
    public function synchronous($user,$encryptedData,$iv)
    {
        $obj = Cache::get($user->id);
        $sessionKey =  $obj->session_key;
        $data = [];
        (new Wx(config('xcx')))->decryptData($sessionKey,$encryptedData,$iv,$data);
        $data = json_decode($data);
        $user->name = $data->nickName;
        $user->avatar = $data->avatarUrl;
        $user->gender = $data->gender;
        $user->infoed = 1;
        $user->save();
        return true;
    }
}